package ch.bfh.fbi.mobicomp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.widget.TextView;
import ch.bfh.fbi.mobicomp.sensorlist.R;
import ch.simplix.android.rumbler.RumblerService;

public class Proximity extends Activity implements SensorEventListener {
	private SensorManager mgr;
	private Sensor light;
	private TextView text;
	private StringBuilder msg = new StringBuilder(2048);
	private WakeLock wl;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		PowerManager powerManager = (PowerManager) this
				.getSystemService(Context.POWER_SERVICE);

		wl = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
				"WakeLock");
		wl.acquire();

		mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
		light = mgr.getDefaultSensor(Sensor.TYPE_LIGHT);
		text = (TextView) findViewById(R.id.text);
		mgr.registerListener(this, light, SensorManager.SENSOR_DELAY_NORMAL);
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		msg.insert(0, sensor.getName()
				+ " accuracy changed: "
				+ accuracy
				+ (accuracy == 1 ? " (LOW)" : (accuracy == 2 ? " (MED)"
						: " (HIGH)")) + "\n");
		text.setText(msg);
		text.invalidate();
	}

	public void onSensorChanged(SensorEvent event) {
		msg.insert(0, "Got a sensor event: " + event.values[0]
				+ " SI lux units\n");
		text.setText(msg);
		new Thread() {
			public void run() {
				Intent rumblerIntent = new Intent(
						RumblerService.RUMBLER_SERVICE);			
				try {
					rumblerIntent.putExtra(RumblerService.PERCENT, 100);
					startService(rumblerIntent);
					Thread.sleep(100);
					rumblerIntent.putExtra(RumblerService.PERCENT, 10);
					startService(rumblerIntent);
					Thread.sleep(250);
					
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				rumblerIntent.putExtra("Cancel", true);
				startService(rumblerIntent);
			}
		}.start();
		text.invalidate();
	}

	@Override
	protected void onDestroy() {
		mgr.unregisterListener(this, light);
		try{
			wl.release();
		}catch (Exception e) {
			//That's ok
		}

		super.onDestroy();
	}
}